package com.rzico.sbl.ui.member

import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityMemberBinding
import com.rzico.sbl.model.MemberData
import com.rzico.sbl.model.MemberFilterData
import com.rzico.sbl.viewmodel.MemberViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadCircleImage
import com.xinnuo.common_ui.utils.addOnScrollChanged
import com.xinnuo.common_ui.utils.showBottomPhoneDialog
import com.xinnuo.slimadapter.SlimAdapter

class MemberActivity : BaseActivity(R.layout.activity_member) {

    private val mBinding by lazy { ActivityMemberBinding.bind(getRootView()) }

    private var mKeyWord = ""
    private var mCardType = ""                   //用户类型
    private var mExchangeFlag = 0                //水票状态
    private var mFilterItem = MemberFilterData() //筛选条件

    override fun getViewModel() = get<MemberViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initLayout()
        initSearch()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
        getViewModel().getSummary()
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关会员信息！"
                }

                recycleList.also { view ->
                    view.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = {
                            getData(0)
                            getViewModel().getSummary()
                        },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    view.addItemDecoration(SpaceTBDecoration(hasHeader = false, bottom = 64f))
                    view.addOnScrollChanged(
                        onShow = { mBinding.memberBottom.bottomShow() },
                        onHide = { mBinding.memberBottom.bottomHide(52f) }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<MemberData>(R.layout.item_member_list) { jector, bean, _ ->
                            jector.apply {
                                text(
                                    R.id.item_member_from,
                                    when (bean.source) {
                                        "applet" -> "小程序"
                                        "app" -> "APP添加"
                                        "pc" -> "后台添加"
                                        else -> ""
                                    }
                                )
                                text(R.id.item_member_card, "NO.${bean.code}")
                                text(R.id.item_member_name, bean.name)
                                text(R.id.item_member_register, bean.mobile)

                                text(R.id.item_member_phone, bean.receiverMobile)
                                text(R.id.item_member_addr, bean.receiverAddress)
                                text(R.id.item_member_time, bean.createDate.getTimeString())
                                text(R.id.item_member_memo, bean.memo)
                                text(R.id.item_member_ticket, bean.exchange)
                                text(R.id.item_member_pledge, bean.mortgage)
                                text(R.id.item_member_borrow, bean.borrowBarrel)
                                text(R.id.item_member_lead, bean.promoter)

                                getView<View>(R.id.item_member_from)
                                    .isGone = bean.source.isNullOrEmpty()
                                getView<View>(R.id.item_member_label01)
                                    .isVisible = bean.paymentMethod == "monthly"
                                getView<View>(R.id.item_member_label02)
                                    .isVisible = bean.cardType == "company"
                                getView<View>(R.id.item_member_label03)
                                    .isVisible = bean.productPriceFlag
                                getView<View>(R.id.item_member_label04)
                                    .isVisible = bean.type == "team"
                                getView<View>(R.id.item_member_label05).isGone =
                                    bean.adminId.isNullOrEmpty() && bean.shippingId.isNullOrEmpty()
                                getView<View>(R.id.item_member_label06).isVisible =
                                    bean.amount.doubleValue == 0.0 && bean.arrears.doubleValue == 0.0
                                getView<View>(R.id.item_member_label07).isVisible =
                                    bean.amount.doubleValue > 0 || bean.arrears.doubleValue > 0
                                getView<View>(R.id.item_member_phone_ll)
                                    .isGone = bean.receiverMobile.isNullOrEmpty()
                                getView<View>(R.id.item_member_addr_ll)
                                    .isGone = bean.receiverAddress.isNullOrEmpty()
                                getView<View>(R.id.item_member_memo_ll)
                                    .isGone = bean.memo.isEmpty()
                                getView<View>(R.id.item_member_lead_ll)
                                    .isGone = bean.promoter.isNullOrEmpty()

                                with<ImageView>(R.id.item_member_logo) {
                                    it.loadCircleImage(bean.logo, R.mipmap.default_user)
                                }

                                with<ImageView>(R.id.item_member_level) {
                                    it.setImageResource(
                                        when (bean.vip) {
                                            "vip1" -> R.mipmap.member_list06
                                            "vip2" -> R.mipmap.member_list07
                                            "vip3" -> R.mipmap.member_list08
                                            "vip4" -> R.mipmap.member_list09
                                            "vip5" -> R.mipmap.member_list10
                                            "vip6" -> R.mipmap.member_list11
                                            "vip7" -> R.mipmap.member_list12
                                            "vip8" -> R.mipmap.member_list13
                                            else -> R.mipmap.member_list05
                                        }
                                    )
                                }

                                clicked(R.id.item_member_call) { showCallDialog(bean.mobile) }

                                clicked(R.id.item_member_ticket_ll) {
                                    startActivityEx<MemberTicketActivity>(
                                        "cardId" to bean.id,
                                        "memberId" to bean.memberId
                                    )
                                }

                                clicked(R.id.item_member_pledge_ll) {
                                    startActivityEx<MemberBucketActivity>(
                                        "cardId" to bean.id,
                                        "memberId" to bean.memberId
                                    )
                                }

                                clicked(R.id.item_member_borrow_ll) {
                                    startActivityEx<MemberBucketActivity>(
                                        "cardId" to bean.id,
                                        "memberId" to bean.memberId
                                    )
                                }

                                clicked(R.id.item_member_more) {
                                    startActivityEx<MemberMoreActivity>(
                                        "cardId" to bean.id,
                                        "memberId" to bean.memberId,
                                        "memberPhone" to bean.mobile
                                    )
                                }

                                clicked {
                                    startActivityEx<MemberDetailActivity>(
                                        "cardId" to bean.id,
                                        "memberId" to bean.memberId,
                                        "memberPhone" to bean.mobile
                                    )
                                }
                            }
                        }
                        .attachTo(view)
                }
            }
    }

    private fun initSearch() {
        mBinding
            .memberSearch
            .apply {
                searchEdit.hint = "请输入姓名、手机号"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        searchEdit.text
                            .isBlank()
                            .conditionElse(
                                actionTrue = { showToast("请输入姓名、手机号") },
                                actionFalse = {
                                    mKeyWord = searchEdit.textTrim
                                    updateList()
                                }
                            )
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    searchEdit.text
                        .isBlank()
                        .conditionElse(
                            actionTrue = { showToast("请输入姓名、手机号") },
                            actionFalse = {
                                mKeyWord = searchEdit.textTrim
                                updateList()
                            }
                        )
                }
            }
    }

    override fun initListener() {
        mBinding.apply {
            memberTypeLl.oneClick {
                getViewModel()
                    .showDropFilter(
                        getIContext(),
                        memberTop,
                        getViewModel().mTypeList,
                        memberType,
                        memberTypeArrow
                    ) {
                        if (it.id.isEmpty()) {
                            memberType.setTextColor(getColorEx(R.color.gray))
                            memberTypeArrow.setImageResource(R.mipmap.icon_member01)
                        } else {
                            memberType.setTextColor(getColorEx(R.color.colorAccent))
                            memberTypeArrow.setImageResource(R.mipmap.icon_member02)
                        }

                        mCardType = it.id
                        updateList()
                    }
            }

            memberTicketLl.oneClick {
                getViewModel()
                    .showDropFilter(
                        getIContext(),
                        memberTop,
                        getViewModel().mTicketList,
                        memberTicket,
                        memberTicketArrow
                    ) {
                        if (it.id == "0") {
                            memberTicket.setTextColor(getColorEx(R.color.gray))
                            memberTicketArrow.setImageResource(R.mipmap.icon_member01)
                        } else {
                            memberTicket.setTextColor(getColorEx(R.color.colorAccent))
                            memberTicketArrow.setImageResource(R.mipmap.icon_member02)
                        }

                        mExchangeFlag = it.id.intValue
                        updateList()
                    }
            }

            memberFilterLl.oneClick {
                getViewModel()
                    .memberFilter(
                        getIContext(),
                        memberTop
                    ) {
                        if (it.filterFlag) {
                            memberFilter.setTextColor(getColorEx(R.color.colorAccent))
                            memberFilterArrow.setImageResource(R.mipmap.icon_member04)
                        } else {
                            memberFilter.setTextColor(getColorEx(R.color.gray))
                            memberFilterArrow.setImageResource(R.mipmap.icon_member03)
                        }

                        mFilterItem = it
                        updateList()
                    }
            }

            btAdd.oneClick {
                startActivityEx<MemberAdressEditActivity>()
            }

            getViewModel()
                .mTotalNum
                .observe(getLifecycleOwner()) {
                    memberTotal.text = it
                }

            getViewModel()
                .mTradeNum
                .observe(getLifecycleOwner()) {
                    memberBuy.text = it
                }
        }

        // 添加会员观察
        observe<String>("memberList") { updateList() }
    }

    private fun showCallDialog(phone: String) = showBottomPhoneDialog(phone)

    /**
     * 会员列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .memberList(
                page = index,
                keyWord = mKeyWord,
                cardType = mCardType,
                exchage = mExchangeFlag,
                filter = mFilterItem,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}